#!/usr/bin/python
# -*- coding: utf-8 -*-

"""登录世纪佳缘"""


import sys
import urllib, urllib2, cookielib
import gzip
import StringIO
import re
import requests
from lxml import html
import monkey


BASE_HEADER = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
               'Accept-Encoding':'gzip,deflate',
               'Accept-Language':'zh-CN,zh;q=0.8',
               'Connection':'keep-alive',
               'User-Agent':'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko',
               }

SESSION = requests.Session()


def gz_decode(data):
    """gzip decode"""
    try:
        compressedstream = StringIO.StringIO(data)
        gziper = gzip.GzipFile(fileobj=compressedstream)
        data = gziper.read()
        return data
    except Exception, e:
        return None


def make_cookie(name, value):
    """cookiejar.set_cookie(make_cookie("name", "value"))"""
    return cookielib.Cookie(
        version=0,
        name=name,
        value=value,
        port=None,
        port_specified=False,
        domain="xxxxx",
        domain_specified=True,
        domain_initial_dot=False,
        path="/",
        path_specified=True,
        secure=False,
        expires=None,
        discard=False,
        comment=None,
        comment_url=None,
        rest=None
    )


def https_auth(cookies):
    passport_url = r'https://passport.jiayuan.com/dologin.php?pre_url=http://www.jiayuan.com/usercp'
    if not cookies:
        return None, None
    PHPSESSID = cookies.get('PHPSESSID')
    post_data = {'name':'baixuexue123@sina.com',
               'password': 'xuebailove321',
               '_s_x_id': PHPSESSID,
               'm_p_l': '1',
               'ljg_login': '1',
               'position': '0',
               'channel': '0',
               'remem_pass': 'on',
               }
    post_data = urllib.urlencode(post_data)
    cj = cookielib.CookieJar()
    for k, v in dict(cookies).iteritems():
        cj.set_cookie(make_cookie(k, v))
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    urllib2.install_opener(opener)
    https_req = urllib2.Request(passport_url, post_data, BASE_HEADER)
    https_req.add_header('Referer','http://login.jiayuan.com/')
    https_req.add_header('Content-Type','application/x-www-form-urlencoded')
    response = urllib2.urlopen(https_req)
    set_cookies = response.info().getallmatchingheaders('Set-Cookie')
    content = response.read()
    if content and set_cookies:
        return set_cookies, gz_decode(content)
    return None, None


def get_redirect_url(page):
    pattern = re.compile(r"top\.location\.href='(\S+?)';")
    s = pattern.findall(page)
    if len(s) > 0:
        return s[0]
    else:
        return None


def login():
    url = r'http://login.jiayuan.com'
    response = SESSION.get(url, headers=BASE_HEADER)
    if response.status_code in (404, 505):return
    cookies = response.cookies
    set_cookies, content = https_auth(cookies)
    return set_cookies, content


if __name__ == '__main__':
    cookies, content = login()
    if cookies:
        for c in cookies:
            val = c[12:].split(';')[0].split('=')
            print val
        #     SESSION.cookies.set(val[0], val[1])
        # for k in SESSION.cookies.keys():
        #     print k
